<template>
  <PageLayout 
    title="编辑虚构电影" 
    description="修改您的虚构电影信息"
  >
    <div v-if="isLoading" class="flex justify-center py-12">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500"></div>
    </div>

    <div v-else-if="error" class="text-center py-8">
      <div class="text-error mb-4">{{ error }}</div>
      <UiButton 
        @click="loadMovie"
        variant="primary"
      >
        重试
      </UiButton>
    </div>

    <div v-else class="space-y-6">
      <!-- 使用 MovieForm 组件 -->
      <MovieForm
        :movie-id="movieId"
        submit-text="更新影片"
        @cancel="$router.go(-1)"
        @submit="handleSubmit"
      />

      <!-- 删除按钮 -->
      <div class="flex justify-end">
        <UiButton
          @click="handleDelete"
          variant="danger"
          :disabled="isUpdating"
        >
          删除影片
        </UiButton>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-background-800 rounded-lg p-6 max-w-md w-full mx-4">
        <h3 class="text-lg font-semibold text-text-primary mb-4">确认删除</h3>
        <p class="text-text-muted mb-6">
          确定要删除这部影片吗？此操作无法撤销。
        </p>
        <div class="flex justify-end gap-3">
          <UiButton
            @click="showDeleteConfirm = false"
            variant="secondary"
          >
            取消
          </UiButton>
          <UiButton
            @click="confirmDelete"
            variant="danger"
            :disabled="isDeleting"
          >
            {{ isDeleting ? '删除中...' : '确认删除' }}
          </UiButton>
        </div>
      </div>
    </div>
  </PageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useMovieStore } from '../store/useMovieStore'
import { useUiStore } from '../store/useUiStore'
import { useDraftStore } from '../store/useDraftStore'
import PageLayout from '../components/layout/PageLayout.vue'
import MovieForm from '../components/movie/MovieForm.vue'
import { UiButton } from '../components/ui'

const route = useRoute()
const router = useRouter()
const movieStore = useMovieStore()
const uiStore = useUiStore()
const draftStore = useDraftStore()

// 获取电影ID
const movieId = Number(route.params.id)

// 状态
const isLoading = ref(true)
const error = ref<string | null>(null)
const showDeleteConfirm = ref(false)
const isDeleting = ref(false)

// 从store获取状态
const { isUpdating } = storeToRefs(movieStore)

// 加载电影数据
const loadMovie = async () => {
  if (!movieId) {
    error.value = '无效的电影ID'
    return
  }

  isLoading.value = true
  error.value = null

  try {
    // 初始化标签系统
    await movieStore.initializeTags()
    
    // 初始化电影表单（编辑模式）
    await movieStore.initializeMovieForm(movieId)

    // 如存在该电影的编辑草稿，则覆盖服务器加载的数据（草稿优先）
    try {
      const draft = draftStore.getEditDraft(movieId)
      if (draft?.data) {
        Object.assign(movieStore.form, JSON.parse(JSON.stringify(draft.data.form)))
        if (draft.data.originalCoverUrl) movieStore.originalCoverUrl = draft.data.originalCoverUrl
        if (draft.data.coverPreview) movieStore.coverPreview = draft.data.coverPreview
        uiStore.showInfo('已从草稿恢复编辑内容')
      }
    } catch (_) {
      // 忽略草稿恢复异常
    }
    
    isLoading.value = false
  } catch (err) {
    console.error('加载电影数据失败:', err)
    error.value = err instanceof Error ? err.message : '加载失败'
    isLoading.value = false
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    await movieStore.updateMovie()
    uiStore.showSuccess('电影更新成功！')
    // 清除当前电影编辑草稿
    if (movieId) {
      draftStore.clearEditDraft(movieId)
    }
    router.push(`/movie/${movieId}`)
  } catch (err) {
    console.error('更新失败:', err)
    uiStore.showError(err instanceof Error ? err.message : '更新失败')
  }
}

// 处理删除
const handleDelete = () => {
  showDeleteConfirm.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    isDeleting.value = true
    await movieStore.deleteMovie()
    uiStore.showSuccess('电影删除成功！')
    router.push('/')
  } catch (err) {
    console.error('删除失败:', err)
    uiStore.showError(err instanceof Error ? err.message : '删除失败')
  } finally {
    isDeleting.value = false
    showDeleteConfirm.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadMovie()
})

// 组件卸载时清理状态
onUnmounted(() => {
  // 如果用户离开编辑页面，清理表单状态
  movieStore.resetForm()
})
</script>
